package com.xxxx.controller;

import com.alibaba.fastjson.JSON;
import com.xxxx.dao.EmpDao;
import com.xxxx.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

/**
 * Created By ShaoXikai on 2022/7/16
 */
@Controller
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private EmpDao empDao;

    @GetMapping("/index")
    public String empIndex() {
        return "welcome";
    }

    @GetMapping("/list")
    public String empList(Model model) {
        model.addAttribute("employeeList", empDao.empList());
        return "employee_list";
    }

    @PostMapping("/add")
    public void empList(Employee employee) {
        empDao.addEmp(employee);
    }

    //查询所有员工，使用js函数动态实现
    @RequestMapping("/jlist")
    public String getAllEmp(Model model) {
        //调用查询所有数据的方法
        Collection<Employee> edAll = empDao.empList();
        //将Java对象转换为json
        String json = JSON.toJSONString(edAll);
        model.addAttribute("employeeList", json);
        return "emp_list";
    }

    //查询指定员工信息
    @GetMapping("/find/{id}")
    public String getById(@PathVariable Integer id, Model model) {
        Employee employee = empDao.getById(id);
        String empJson = JSON.toJSONString(employee);
        model.addAttribute("employeeList", empJson);
        return "emp_list";
    }
    /*
    @RequestMapping({"/jlist", "/find/{id}"})
    public String getAllEmp(Model model, @PathVariable Integer id) {
        //调用查询所有数据的方法
        if (id == null) {
            Collection<Employee> edAll = empDao.empList();
            //将Java对象转换为json
            String json = JSON.toJSONString(edAll);
            model.addAttribute("employeeList", json);
            return "emp_list";
        } else {
            Employee employee = empDao.getById(id);
            String empJson = JSON.toJSONString(employee);
            model.addAttribute("employeeList", empJson);
            return "emp_list";
        }
    }
     */
}
